<?php
/**
 * Created by IntelliJ IDEA.
 * User: LZ
 * Date: 2018/8/29
 * Time: 14:30
 */
header("content-type:text/html;charset=utf-8");
include_once dirname(dirname(dirname(__FILE__))) . "/nn_logic/nl_common.func.php";

$config = array(
    'host' => '127.0.0.1:3306',
    "user" => 'root',
    "passwd" => 'root',
    "db_name" => 'jx_cms',
    "db_type" => NP_DB_TYPE_MYSQL,
    "db_log" => NP_DB_LOG_SQL_DEBUG_EXPLAIN
);
define('START_NUM', 0);//起始数
define("RUN_SQL_NUM", 300);//一次性运行的SQL数
define("STOP_RUN_NUM",0);//运行最大条数

class script_jx_video
{
    public $dc = null;
    public $cms_db = null;
    public $vod_table = "nns_vod";
    public $vod_bind_index_table = "nns_vod_index_bind";
    public $vod_index_table = "nns_vod_index";
    public $vod_media_table = "nns_vod_media";
    public $c2_task_table = "nns_mgtvbk_c2_task";

    public function __construct($config)
    {
        $this->dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE | NL_DB_READ,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));

        $cms_db = np_db_factory_create($config);
        if (!$cms_db->open())
        {
            die('连接数据库错误');
        }
        $this->cms_db = $cms_db;
    }
    /**
     * 执行脚本
     */
    public function run()
    {
        $num = START_NUM;
        while ($data = $this->get_cms_info($num))
        {
            foreach ($data as $value)
            {
                //根据原始ID查询播控上媒资名称
                $name_sql = "SELECT nns_name from nns_vod where nns_asset_import_id = '{$value['nns_original_id']}'";
                $name_re = nl_query_by_db($name_sql,$this->dc->db());
                //set-1 修改主媒资注入ID
                //播控平台--查询注入CDN成功的原始主媒资并获取到它的ID，获取创建时间最晚的那个
                //$sql = "select v.nns_id,v.nns_asset_import_id,v.nns_name,v.nns_create_time from nns_vod as v left join nns_mgtvbk_c2_task as c2 on v.nns_id=c2.nns_ref_id where c2.nns_status=0 and v.nns_name='{$value['nns_name']}' and v.nns_deleted != 1 and (v.nns_asset_import_id like '%youku%' or v.nns_asset_import_id like '%TD%') and v.nns_asset_import_id != '{$value['nns_original_id']}' order by v.nns_create_time desc";
                $sql = "select v.nns_id,v.nns_asset_import_id,v.nns_name,v.nns_create_time from nns_vod as v left join nns_mgtvbk_c2_task as c2 on v.nns_id=c2.nns_ref_id where 
                  c2.nns_status=0 and v.nns_name = '{$name_re[0]['nns_name']}' and v.nns_deleted != 1 and 
                  (v.nns_asset_import_id like '%youku%' or v.nns_asset_import_id like '%TD%') and v.nns_asset_import_id != '{$value['nns_original_id']}' order by v.nns_create_time desc";
                $new_vod = nl_query_by_db($sql,$this->dc->db());
                if(!is_array($new_vod))
                {
                    //记录出错的数据
                    file_put_contents(dirname(__FILE__).'/one_continue.txt', var_export($sql,true) . "\r\n", FILE_APPEND);
                    file_put_contents(dirname(__FILE__).'/inventory_data.txt', $value['nns_original_id'] . "----" . $value['nns_name'] . "\r\n", FILE_APPEND);
                    continue ; //没有获取到标识没有相关数据  退出
                }
                if(count($new_vod) >= 2) //记录导入重复的数据
                {
                    file_put_contents(dirname(__FILE__).'/repeat.txt', var_export($new_vod,true) . "\r\n", FILE_APPEND);
                }
                //修改CMS的注入ID，原始ID不动，切换回去可以保持播放
                $update_sql = "update nns_vod set nns_asset_import_id='{$new_vod[0]['nns_id']}' where nns_id='{$value['nns_id']}'";
                //nl_execute_by_db($update_sql,$this->cms_db);
                //备份主媒资还原Sql
                //$backup_sql = "update nns_vod set nns_asset_import_id = '{$value['nns_asset_import_id']}' WHERE nns_id='{$value['nns_id']}';";
                //$this->nn_backup($backup_sql);
                //set-2 修改分集与片源的注入ID
                //CMS平台---获取当前修改的分集与片源信息
                $old_sql = "select i.nns_id as i_id,i.nns_import_id as i_import_id,m.nns_id as m_id,m.nns_import_id as m_import_id,b.nns_index from nns_vod_index as i LEFT JOIN nns_vod_media as m on m.nns_vod_index_id=i.nns_id INNER JOIN nns_vod_index_bind as b on i.nns_id=b.nns_index_id where b.nns_vod_id='{$value['nns_id']}'";
                $old_info =  nl_query_by_db($old_sql,$this->cms_db);
                if(!is_array($old_info))
                {
                    //记录出错的数据
                    file_put_contents(dirname(__FILE__).'/two_continue.txt', var_export($old_sql,true) . "\r\n", FILE_APPEND);
                    continue;
                }
                //播控平台---$new_vod中获取分集与片源信息
                $new_sql = "select i.nns_id as i_id,i.nns_import_id as i_import_id,m.nns_id as m_id,m.nns_import_id as m_import_id,i.nns_index from nns_vod_index as i LEFT JOIN nns_vod_media as m on i.nns_id = m.nns_vod_index_id WHERE i.nns_vod_id = '{$new_vod[0]['nns_id']}'";
                $new_info = nl_query_by_db($new_sql,$this->dc->db());//echo '<pre>';var_dump($new_info);die;
                if(!is_array($new_info))
                {
                    //记录出错的数据
                    file_put_contents(dirname(__FILE__).'/three_continue.txt', var_export($new_sql,true) . "\r\n", FILE_APPEND);
                    continue;
                }
                //剔除播控平台认为错误的数据
                foreach ($new_info as $val)
                {
                    //查询C2任务及C2队列未删除的任务
                    $sql = "select * from nns_mgtvbk_c2_task ";
                }

                $arr_new_info = np_array_rekey($new_info,'nns_index');
                foreach ($old_info as $info)
                {
                    if(isset($arr_new_info[$info['nns_index']]))
                    {
                        $u_info = $arr_new_info[$info['nns_index']];
                        $index_update_sql = "update nns_vod_index set nns_import_id = '{$u_info['i_id']}' where nns_id = '{$info['i_id']}'";echo $index_update_sql;echo '<br/>';
                        //nl_execute_by_db($index_update_sql,$this->cms_db);
                        //备份分集还原SQL
                        //$backup_sql = "update nns_vod_index set nns_import_id = '{$info['i_import_id']}' WHERE nns_id='{$info['i_id']}';";
                        //$this->nn_backup($backup_sql);
                        if(!empty($info['m_id']))
                        {
                            $media_update_sql = "update nns_vod_media set nns_import_id = '{$u_info['m_id']}' where nns_id = '{$info['m_id']}'";echo $media_update_sql;echo '<hr/>';
                            //nl_execute_by_db($media_update_sql,$this->cms_db);
                            //备份片源还原SQL
                            //$backup_sql = "update nns_vod_media set nns_import_id = '{$info['m_import_id']}' WHERE nns_id='{$info['m_id']}';";
                            //$this->nn_backup($backup_sql);
                        }
                    }
                }
            }
            $num += RUN_SQL_NUM;die;
        }
    }
    /**
     * 获取CMS信息
     */
    public function get_cms_info($num)
    {
        if(STOP_RUN_NUM !== 0)
        {
            if($num >= STOP_RUN_NUM)
            {
                return false;
            }
        }
        if((STOP_RUN_NUM === 0) || (STOP_RUN_NUM - $num > RUN_SQL_NUM))
        {
            $get_num = RUN_SQL_NUM;
        }
        else
        {
            $get_num = STOP_RUN_NUM - $num;
        }
        //$sql = "select nns_id,nns_name,nns_original_id,nns_asset_import_id from " . $this->vod_table . " where nns_original_id not like '%youku%' order by nns_original_id asc limit {$num},{$get_num}";
        $sql = "select nns_id,nns_name,nns_original_id,nns_asset_import_id from nns_vod where nns_id='5ad48ec927dbf34e0e12e6dc7a70f212'";
        //echo $sql;echo '<hr/>';
        $result = nl_query_by_db($sql, $this->cms_db);
        if (!is_array($result))
        {
            return false;
        }
        return $result;
    }
    /**
     * 备份SQL
     * @param string $msg
     */
    public function nn_backup($msg)
    {
        $str_log_dir = dirname(__FILE__) . '/';
        if (empty($msg))
        {
            return false;
        }

        //写入日志文件
        $str_log_file = $str_log_dir . date('H') . '.txt';
        if (!is_dir($str_log_dir))
        {
            mkdir($str_log_dir, 0777, true);
        }
        file_put_contents($str_log_file, $msg . "\r\n", FILE_APPEND);
    }
}

$script_jx_video = new script_jx_video($config);
$script_jx_video->run();